import { Button, Space, Table, Tag, Image, Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { bannerGet, bannerDel } from "@/api/cake";
import qs from 'query-string'
import {connect} from 'react-redux'

const BannerList = (props) => {
  let [data, setData] = useState([]);
  console.log(props);
  let bool = props.user.userInfo.rolecode!=='root'
  const columns = [
    //控制表格结构
    {
      title: "ID",
      dataIndex: "objectId",
      key: "objectId",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "活动名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "活动封面",
      dataIndex: "poster",
      key: "poster",
      render: (url) => {
        return <Image src={url} height={60} />;
      },
    },
    {
      title: "活动链接",
      dataIndex: "link",
      key: "link",
      render: (link, record) => {
        if (record.type == 1) {
          return (
            <a href={link} target="_blank">
              点击预览
            </a>
          );
        }
        return link;
      },
    },
    {
      title: "活动类型",
      key: "type",
      dataIndex: "type",
      render: (type) => {
        let color = type == 1 ? "geekblue" : "green";
        let text = type == 1 ? "外联活动" : "商品活动";
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record, index) => (
        <Space size="middle">
          <Button type="primary" onClick={()=>{handleEdit(record)}}>编辑</Button>
          <Button
            type="primary"
            danger
            onClick={() => {
              handleDel(record.objectId, index);
            }}
            disabled={bool}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  let handleDel = (objectId, index) => { //删除
    Modal.confirm({
      title: "删除后数据无法找回",
      icon: <ExclamationCircleOutlined />,
      content: "你确定不是手抖了嘛？",
      okText: "确认",
      cancelText: "取消",
      onOk: () => {
        console.log("点了确定");
        bannerDel(objectId).then(() => {
          data.splice(index, 1);
          setData([...data]);
        });
      },
    });
  };

  let handleEdit = (record)=>{
    props.history.push({
      pathname:'/admin/banner/edit',
      search:qs.stringify(record)
    })
  }

  useEffect(() => {
    bannerGet().then((res) => {
      setData(res.data.results);
    });
  }, []);
  return (
    <Table
      columns={columns}
      dataSource={data}
      pagination={{ pageSize: 5 }}
      rowKey="objectId"
    />
  );
};

export default connect(({user})=>({user}))(BannerList);
